package cn.msqweb.controller;


import cn.msqweb.entity.Category;
import cn.msqweb.model.Result;
import cn.msqweb.service.CategoryService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;


/**
 * 商品类目控制层
 */
@Api(tags = "商品类目接口管理")
@RequestMapping("prod/category")
@RestController
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    @ApiOperation("查询商品类目集合")
    @GetMapping("table")
    @PreAuthorize("hasAuthority('prod:category:page')")
    public Result<List<Category>> loadCategoryList() {
        List<Category> list = categoryService.list(new LambdaQueryWrapper<Category>()
                .orderByDesc(Category::getSeq)
        );
        return Result.success(list);
    }

//    prod/category/listCategory
    @ApiOperation("查询商品一级类目集合")
    @GetMapping("listCategory")
    @PreAuthorize("hasAuthority('prod:category:page')")
    public Result<List<Category>> loadFirstCategoryList() {
        List<Category> list = categoryService.list(new LambdaQueryWrapper<Category>()
                .eq(Category::getParentId,0)
                .orderByDesc(Category::getSeq)
        );
        return Result.success(list);
    }

    @ApiOperation("新增商品类目")
    @PostMapping
    @PreAuthorize("hasAuthority('prod:category:save')")
    public Result<String> saveCategory(@ApiParam("商品类目对象") @RequestBody Category category) {
        Boolean saved = categoryService.saveCategory(category);
        return Result.handler(saved);
    }

    @ApiOperation("根据标识查询商品类目信息")
    @GetMapping("info/{id}")
    @PreAuthorize("hasAuthority('prod:category:info')")
    public Result<Category> loadCategoryInfo(@ApiParam("商品类目标识") @PathVariable Long id) {
        Category category = categoryService.getById(id);
        return Result.success(category);
    }

    @ApiOperation("修改商品类目信息")
    @PutMapping
    @PreAuthorize("hasAuthority('prod:category:update')")
    public Result<String> modifyCategory(@ApiParam("商品类目对象") @RequestBody Category category) {
        Boolean modified = categoryService.modifyCategory(category);
        return Result.handler(modified);
    }

    @ApiOperation("删除商品类目")
    @DeleteMapping("{categoryId}")
    @PreAuthorize("hasAuthority('prod:category:delete')")
    public Result<String> removeCategory(@ApiParam("商品类目标识") @PathVariable Long categoryId) {
        Boolean removed = categoryService.removeCategoryById(categoryId);
        return Result.handler(removed);
    }
}
